package com.wsjc.web.interceptors;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;

/**
 * TODO... 无注释
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {
	private static final Log log = LogFactory.getLog(AuthInterceptor.class);
	@Autowired
//	private RpUserInfoService rpUserInfoService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		/*if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
			String token = request.getHeader("token");
			if (StringUtils.isBlank(token)) {
				String token1 = request.getParameter("token");
				if (StringUtils.isBlank(token1)) {
					ApiCommonResultVo resultVo = new ApiCommonResultVo(-1, "请求失败！缺少token参数！", "");
					writeErrorMsg(response, resultVo);
					return false;
				}
				token = token1;
			}

			String clientId = "APP";
			Map<String, Object> json = rpUserInfoService.checkToken(clientId, token);
			if (json != null) {
				Object userNo = json.get("userNo");
				Object userType = json.get("userType");
				
				if (userNo != null) {
					request.setAttribute("userNo", userNo);
					request.setAttribute("userType", userType);
				}
			} else {
				ApiCommonResultVo resultVo = new ApiCommonResultVo(-10, "鉴权失败！", "");
				writeErrorMsg(response, resultVo);
				return false;
			}
		}*/
		return super.preHandle(request, response, handler);
	}

	public void writeErrorMsg(HttpServletResponse response, Object obj) throws IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=UTF-8");
		PrintWriter writer = response.getWriter();
		log.info("=========>" + JSONObject.toJSONString(obj));
		writer.print(JSONObject.toJSONString(obj));
	}

	/**
	 * 该方法将在Controller执行之后，返回视图之前执行，ModelMap表示请求Controller处理之后返回的Model对象，所以可以在
	 * 这个方法中修改ModelMap的属性，从而达到改变返回的模型的效果。
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

	}

	/**
	 * 该方法将在整个请求完成之后，也就是说在视图渲染之后进行调用，主要用于进行一些资源的释放
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
	}

	@Override
	public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		super.afterConcurrentHandlingStarted(request, response, handler);
	}

}
